package org.jingouzhui.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jingouzhui.domain.strategy.model.entity.StrategyEntity;
import org.jingouzhui.domain.strategy.repository.IStrategyRepository;
import org.jingouzhui.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.jingouzhui.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import org.jingouzhui.types.common.Delimiter;
import org.jingouzhui.types.enums.ResponseCode;
import org.jingouzhui.types.exception.AppException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
* @description: 黑名单抽奖责任链
* @author: jingouzhui
* @date: 2025/4/29 12:31
*/

@Slf4j
@Component("rule_blacklist")
public class RuleBlackListLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    protected String ruleModel() {
        return DefaultLogicChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }

    @Override
    public DefaultLogicChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("责任链-黑名单开始处理抽奖流程，userId：{}，strategyId：{}",userId,strategyId);
        //1.根据strategyId查询策略
        StrategyEntity strategy = strategyRepository.queryStrategyByStrategyId(strategyId);
        //2.获取该策略对应的规则有哪些
        String ruleModels = strategy.getRuleModels();
        if (StringUtils.isEmpty(ruleModels)) {
            throw new AppException(strategyId+"对应的策略规则为空");
        }
        //3.查看是否包含黑名单，如果包含则获取对应的awardId返回否则交给下一个责任链处理
        String result = Arrays.stream(ruleModels.split(Delimiter.COMMA)).filter(e -> e.equals(ruleModel())).findFirst().orElse(null);
        if (StringUtils.isNotEmpty(result)) {

            //查询规则值配置
            String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleModel());
            String[] split = ruleValue.split(Delimiter.COLON);
            if (split == null || split.length != 2) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(),ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            Integer awardId = Integer.parseInt(split[0]);
            long blackUser = Arrays.stream(split[1].split(Delimiter.COMMA)).filter(e -> e.equals(userId)).count();
            if (blackUser > 0) {
                log.info("责任链-黑名单接管抽奖流程，userId:{}，strategyId：{},rule_model:{}",userId,strategyId,ruleModel());
                return DefaultLogicChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModel())
                        .build();
            }
        }
        //交给其他责任链处理
        log.info("责任链-黑名单放行抽奖流程，交给其他责任链处理，userId:{}，strategyId：{},rule_model:{}",userId,strategyId,ruleModel());
        return next().logic(userId,strategyId);
    }
}
